package com.qmx.launcher.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.RectF;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;

import com.open.androidtvwidget.bridge.RecyclerViewBridge;
import com.open.androidtvwidget.leanback.adapter.GeneralAdapter;
import com.open.androidtvwidget.leanback.recycle.LinearLayoutManagerTV;
import com.open.androidtvwidget.leanback.recycle.RecyclerViewTV;
import com.open.androidtvwidget.utils.OPENLOG;
import com.open.androidtvwidget.view.MainUpView;
import com.qmx.launcher.QMXApplication;
import com.qmx.launcher.R;
import com.qmx.launcher.adapter.FileRecyclerViewPresenter;
import com.qmx.launcher.bean.ContactModel;
import com.qmx.launcher.utils.RealmUtils;
import com.qmx.launcher.view.NavigationCursorView;
import com.qmx.launcher.view.NavigationLinearLayout;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import app.dinus.com.itemdecoration.LinearDividerItemDecoration;
import io.realm.Realm;
import io.realm.RealmList;

/**
 * date: 2018/9/18
 * description: FileDialogFragment
 **/
public class FileDialogFragment extends DialogFragment implements RecyclerViewTV.OnItemListener, RecyclerViewTV.OnChildViewHolderSelectedListener {


    private Dialog mDialog;
    private Context mContext;
    // 移动边框.
    MainUpView mainUpView1;
    private RecyclerViewBridge mRecyclerViewBridge;
    private NavigationLinearLayout mNavigationLinearLayout;
    private NavigationCursorView mNavigationCursorView;
    private List<String> data = new ArrayList<>();
    private RecyclerViewTV mRecyclerView;
    private View oldView;
    private FileRecyclerViewPresenter mRecyclerViewPresenter;
    private GeneralAdapter mGeneralAdapter;
    private int roomId;
    private int password;

    private Realm defaultRealm;
    private RealmList<ContactModel> itemList;
    private RealmUtils realmUtils;

    private String filePath;
    private List<String> datas = new ArrayList<>();
    private List<String> paths = new ArrayList<>();


    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Activity activity = getActivity();
        final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        LayoutInflater inflater = activity.getLayoutInflater();
        View view = inflater.inflate(R.layout.pop_meeting_layout, null);
        builder.setView(view);
        mContext = activity.getApplicationContext();
        defaultRealm = QMXApplication.getRealmInstance();
        realmUtils = new RealmUtils(defaultRealm);

        data.add("排列顺序");
        data.add("按时间");
        data.add("按类型");
        initUI(view);
        mDialog = builder.create();

        //mDialog.setCancelable(false);
        //mDialog.setCanceledOnTouchOutside(false);

        return mDialog;
    }

    private void initUI(View view) {
        OPENLOG.initTag("", true); // 测试LOG输出.
        // 初始化标题栏.
        initAllTitleBar(view);
        // 初始化viewpager.
        //        initAllViewPager(view);
        // 初始化移动边框.
        //        initMoveBridge(view);
    }

    private NavigationLinearLayout.NavigationListener mNavigationListener = new NavigationLinearLayout.NavigationListener() {
        @Override
        public void onNavigationChange(int pos, int keyCode) {
            switch (keyCode) {
                case KeyEvent.KEYCODE_DPAD_LEFT:
                case KeyEvent.KEYCODE_DPAD_RIGHT: //模拟刷新内容区域
                    Toast.makeText(getContext(), "我是内容显示区域，当前页面为：" + pos + "，左右切换内容，上键回到导航栏", Toast.LENGTH_SHORT).show();
                    break;
                case KeyEvent.KEYCODE_DPAD_UP:
                case KeyEvent.KEYCODE_DPAD_DOWN:
                    break;
            }
        }
    };

    private void initAllTitleBar(View view) {
        mNavigationLinearLayout = (NavigationLinearLayout) view.findViewById(R.id.mNavigationLinearLayout_id);
        mNavigationCursorView = (NavigationCursorView) view.findViewById(R.id.mNavigationCursorView_id);
        mNavigationLinearLayout.setDataList(data);
        //        mNavigationLinearLayout.setNavigationListener(mNavigationListener);
        mNavigationLinearLayout.setNavigationCursorView(mNavigationCursorView);
        mNavigationLinearLayout.requestFocus();

        mRecyclerView = (RecyclerViewTV) view.findViewById(R.id.recycler_view);
        mainUpView1 = (MainUpView) view.findViewById(R.id.mainUpView1);
        mainUpView1.setEffectBridge(new RecyclerViewBridge());
        // 注意这里，需要使用 RecyclerViewBridge 的移动边框 Bridge.
        mRecyclerViewBridge = (RecyclerViewBridge) mainUpView1.getEffectBridge();
        mRecyclerViewBridge.setUpRectResource(R.drawable.blue_arrow);
        float density = getResources().getDisplayMetrics().density / 2;
        RectF receF = new RectF(getDimension(R.dimen.w_55) * density, getDimension(R.dimen.h_5) * density,
                getDimension(R.dimen.w_5) * density, getDimension(R.dimen.h_5) * density);
        mRecyclerViewBridge.setDrawUpRectPadding(receF);

        saveOrUpdate();
        recyclerViewLinerLayout(RecyclerView.VERTICAL);
        mRecyclerView.setOnItemListener(this);
        // item 单击事件处理.
        mRecyclerView.setOnItemClickListener(new RecyclerViewTV.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerViewTV parent, View itemView, int position) {
                Toast.makeText(mContext, "点击位置" + position, Toast.LENGTH_SHORT).show();
                //                startActivity(new Intent(mContext, CallContactActivity.class));
                //                FileDisplayActivity.show(getContext(), getFilePath(position));
            }
        });
    }

    public void saveOrUpdate() {
        final List<ContactModel> list = new ArrayList<>();
        for (int i = 0; i < 20; i++) {
            ContactModel contactModel = new ContactModel();
            contactModel.setName("修改 " + i);
            contactModel.setMobile(123456789 + i);
            contactModel.setMdate(new Date());
            contactModel.setId(i);
            list.add(contactModel);
        }
        realmUtils.insertOrUpdateBatch(list);

        defaultRealm.executeTransactionAsync(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                //                realmUtils.insertOrUpdateBatch(list);
                //                    realm.copyToRealmOrUpdate(contactModel);
                //                                                         parentContact.getItemList().add(contactModel);
                //                realm.copyToRealmOrUpdate(list);
            }
        });
    }

    private void recyclerViewLinerLayout(int orientation) {
        LinearLayoutManagerTV layoutManager = new LinearLayoutManagerTV(getContext());
        layoutManager.setOrientation(orientation);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerViewPresenter = new FileRecyclerViewPresenter(defaultRealm.where(ContactModel
                .class).findAll());
        mGeneralAdapter = new GeneralAdapter(mRecyclerViewPresenter);
        mRecyclerView.setAdapter(mGeneralAdapter);
        mRecyclerView.setHasFixedSize(true);
        LinearDividerItemDecoration dividerItemDecoration = new LinearDividerItemDecoration(
                getContext(), LinearDividerItemDecoration.LINEAR_DIVIDER_VERTICAL);
        mRecyclerView.addItemDecoration(dividerItemDecoration);
        //        mRecyclerView.setSelectedItemOffset(10, 10); // 测试移动间距.
        //        mRecyclerView.setFocusable(true);
        mRecyclerView.setDefaultSelect(0);


    }

    private float getDimension(int id) {
        return getResources().getDimension(id);
    }


    @Override
    public void onItemPreSelected(RecyclerViewTV parent, View itemView, int position) {
        mRecyclerViewBridge.setUnFocusView(itemView);
    }

    @SuppressLint("ResourceAsColor")
    @Override
    public void onItemSelected(RecyclerViewTV parent, View itemView, int position) {
        mRecyclerViewBridge.setFocusView(itemView, 1.0f);
        oldView = itemView;
    }

    @Override
    public void onReviseFocusFollow(RecyclerViewTV parent, View itemView, int position) {
        mRecyclerViewBridge.setFocusView(itemView, 1.0f);
        oldView = itemView;
    }

    @Override
    public void onChildViewHolderSelected(RecyclerView parent, RecyclerView.ViewHolder vh, int position) {
        parent.findViewHolderForAdapterPosition(position).itemView.setFocusable(true);
    }

    private String getFilePath(int position) {
        String path = null;
        switch (position) {
            case 0:
                path = "http://vip.smartqmx.com/uploads/word.docx";
                break;
            case 1:
                path = "/storage/emulated/0/test.docx";
                break;
            case 2:
                path = "/storage/emulated/0/test.txt";
                break;
            case 3:
                path = "/storage/emulated/0/test.xlsx";
                break;
            case 4:
                path = "/storage/emulated/0/test.pptx";
                break;
            case 5:
                path = "/storage/emulated/0/test.pdf";
                break;
        }
        return path;
    }
}
